package com.dream.service.user.web.processor.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.dream.common.model.response.BaseResponse;
import com.dream.common.model.response.ErrorCode;
import com.dream.common.model.result.AppResultBuilder;
import com.dream.service.image.bean.ImgUpS3Response;
import com.dream.service.image.impl.ImageServiceImpl;
import com.dream.service.user.api.TelCodeService;
import com.dream.service.user.api.UserService;
import com.dream.service.user.domain.entity.User;
import com.dream.service.user.domain.model.UserModel;
import com.dream.service.user.web.model.FieldSchema;
import com.dream.service.user.web.model.Param;
import com.dream.service.user.web.processor.RequestProcessor;
import com.dream.service.user.web.processor.exception.ParamException;
import com.dream.service.user.web.processor.param.ParamProcessor;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by kangd on 2016/3/24.
 */
class UserRequestProcessor implements RequestProcessor {

    UserService userService;

    TelCodeService telCodeService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public TelCodeService getTelCodeService() {
        return telCodeService;
    }

    public void setTelCodeService(TelCodeService telCodeService) {
        this.telCodeService = telCodeService;
    }

    @Override
    public JSONObject processor(HttpServletRequest req) {
        JSONObject result = new JSONObject();
        String cmd = req.getParameter(Param.CMD);
        try {
            if (cmd.equals(Param.UserCMD.USER_DETAIL)) {
                this.getUserDetail(req, result);
            }else if (cmd.equals(Param.UserCMD.USER_SIGNUP)) {
                this.signUp(req, result);
            }else if (cmd.equals(Param.UserCMD.USER_LOGIN)) {
                this.login(req, result);
            }else if (cmd.equals(Param.UserCMD.USER_THIRD_PARTY_LOGIN)) {
                this.trdPtyLogin(req, result);
            }else if (cmd.equals(Param.UserCMD.USER_SIGNOUT)) {
                this.signOut(req, result);
            }else if (cmd.equals(Param.UserCMD.USER_MODIFY_INFO)) {
                this.modifyUserInfo(req, result);
            }else if (cmd.equals(Param.UserCMD.USER_FORGET_PASSWORD)){
                this.forgetPasswd(req, result);
            }else if (cmd.equals(Param.UserCMD.USER_MODIFY_PASSWORD)){
                this.modifyPasswd(req, result);
            } else if (cmd.equals(Param.UserCMD.USER_MODIFY_FORGET_PASSWORD)){
                this.modifyFgtPwd(req, result);
            } else if(cmd.equals(Param.UserCMD.USER_UPLOAD_ICON)){
                this.uploadIcon(req,result);
            }else if(cmd.equals(Param.UserCMD.USER_THIRD_PARTY_LOGIN_BIND_EMAIL)){
                this.getThirdPartyLoginEmail(req, result);
            } else if(cmd.equals(Param.UserCMD.USER_INVITE_CODE)){
                this.getUseInviteCode(req,result);
            }else {
                AppResultBuilder.buildCmdErrorResult(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppResultBuilder.buildResult(result,"",false, ErrorCode.UNKOWN);
        }
        return result;
    }

    // http://motif.evermarker.com/user?cmd=detail&pin=e3dfbc79aebe4c40bc520c20b90ff07f
    //取详情
    public void getUserDetail(HttpServletRequest req,JSONObject result){
        String pin = req.getParameter(FieldSchema.PIN);
        if(StringUtils.isEmpty(pin) ){
            AppResultBuilder.buildParamErrorResult(result,"pin null","");
            return;
        }
        BaseResponse<User> response = null;
        try {
            response = userService.getUserDetailInfo(pin);
            if (response!=null && response.isSuccess()) {
                AppResultBuilder.buildSucResult(result,response.getResult());
            }else{
                AppResultBuilder.buildErrorResult(result, response.getError_code(), response.getError_msg(),"");
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppResultBuilder.buildProcessErrorResult(result, ErrorCode.PROCESS_ERROR.getError_msg(), "Service Error");
        }

    }

    // http://motif.evermarker.com/user?cmd=signup&uuid=199999999999&email=kangdong@evermarker.net&pw=dfafdasEFDdadfa&nick=kangdong
    //注册
    public void signUp(HttpServletRequest req,JSONObject result){
        String uuid = req.getParameter(FieldSchema.UUID);
        String email = req.getParameter(FieldSchema.EMAIL);
        String nickname = req.getParameter(FieldSchema.NICKNAME);
        String passwd = req.getParameter(FieldSchema.PASSWD);
        String src = req.getParameter(FieldSchema.SOURCE);
        if(StringUtils.isEmpty(uuid) || StringUtils.isEmpty(email) ||
                StringUtils.isEmpty(nickname) || StringUtils.isEmpty(passwd)){
            AppResultBuilder.buildParamErrorResult(result,"param null","");
            return;
        }
        if(nickname.length()>100){
            AppResultBuilder.buildParamErrorResult(result,"nickname is too long","nickname must less than 100");
            return;
        }
        if(!email.matches("^[.a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")){
            AppResultBuilder.buildParamErrorResult(result,"please input right email","please input right email");
            return;
        }
        try {
            BaseResponse<User> response = userService.signUp(uuid, email, nickname, passwd,src);
            if (response!=null && response.isSuccess()) {
                AppResultBuilder.buildSucResult(result,response.getResult());
            }else if(response.getError_code() == ErrorCode.USERSTATUS_REGISTERED.getCode()){
                //注册过
                AppResultBuilder.buildErrorResult(result,response.getError_code(),response.getError_msg(),response.getError_msg());
            }else{
                AppResultBuilder.buildErrorResult(result, response.getError_code(), response.getError_msg(), "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppResultBuilder.buildProcessErrorResult(result,  ErrorCode.PROCESS_ERROR.getError_msg(), "Service Error");
        }

    }

    // http://motif.evermarker.com/user?cmd=login&uuid=123838838&email=kangdong@evermarker.net&pw=dfafdasEFDdadfa
    //登录
    public void login(HttpServletRequest req,JSONObject result){
        String email = req.getParameter(FieldSchema.EMAIL);//电话号码
        String uuid = req.getParameter(FieldSchema.UUID);
//        String token = req.getParameter(FieldSchema.TOKEN);
        String code = req.getParameter(FieldSchema.TEL_CODE);
        String src = req.getParameter(FieldSchema.SOURCE);
        if(StringUtils.isEmpty(uuid)){
            AppResultBuilder.buildParamErrorResult(result,"uuid is null","unvalid user");
            return ;
        }
        if(StringUtils.isEmpty(email) ){
            AppResultBuilder.buildParamErrorResult(result,"email is null","your email was entered incompletely");
            return;
        }
        String userName = req.getParameter(FieldSchema.NICKNAME);
        if(StringUtils.isEmpty(userName)){
            int tel_len = email.length();
            userName = "OBOR-".concat(email.substring(tel_len-4,tel_len));
        }
         String password = req.getParameter(FieldSchema.PASSWD);
        if(StringUtils.isEmpty(password)){
            AppResultBuilder.buildParamErrorResult(result,"password is null","your email or password was entered incompletely");
            return ;
        }
        boolean debug = "true".equals(req.getParameter("debug"));
          //check短信验证码是否正确
//        if(telCodeService!=null) {
//            BaseResponse<Boolean> validresponse = telCodeService.validCode(tel, code);
//            if (validresponse != null && ErrorCode.OK.getCode() != validresponse.getError_code()) {
//                AppResultBuilder.buildErrorResult(result, ErrorCode.PARAM_ERROR.getCode(), "please check your code", "");
//                return;
//            }
//        }
            try {
                BaseResponse<User> response = userService.login(uuid, email, password);
                if(debug){
                    result.put("request","uuid:"+uuid+"\temail:"+email+"\tpassword:"+password);
                    result.put("rpc_result",JSONObject.toJSONString(response));
                }
                if (response != null && response.isSuccess()) {
                    if (ErrorCode.USERSTATUS_REGISTERED.getCode() == response.getError_code()) {//如果没有用户，则注册
//                        response = userService.signUp(uuid, tel, userName, "", src);
//                        if (response != null && response.isSuccess()) {
//                            AppResultBuilder.buildSucResult(result, response.getResult());
//                        } else {
                            AppResultBuilder.buildErrorResult(result, ErrorCode.PARAM_ERROR.getCode(), "please check you mail and password", "your email or password was entered incorrectly");
//                        }

                    }else{ //登陆
                        AppResultBuilder.buildSucResult(result, response.getResult());
                    }
                } else {
                    AppResultBuilder.buildErrorResult(result, response.getError_code(), response.getError_msg(), "your email or password was entered incorrectly");
                }
            } catch (Exception e) {
                e.printStackTrace();
                AppResultBuilder.buildProcessErrorResult(result, ErrorCode.PROCESS_ERROR.getError_msg(), "your email or password was entered incorrectly");
            }
    }

    // http://motif.evermarker.com/user?cmd=tplogin&uuid=199999999999&type=facebook&reinfo=reinfo
    // 第三方登录
    public void trdPtyLogin(HttpServletRequest req,JSONObject result){
        String uuid = req.getParameter(FieldSchema.UUID);
        String loginTypeStr = req.getParameter(FieldSchema.LOGIN_TYPE);
        String returnInfo = req.getParameter(FieldSchema.RETURN_INFO);
        String src = req.getParameter(FieldSchema.SOURCE);
        if(StringUtils.isEmpty(uuid) || StringUtils.isEmpty(loginTypeStr) || StringUtils.isEmpty(returnInfo)){
            AppResultBuilder.buildParamErrorResult(result,"");
            return;
        }
        System.out.println(new Date()+returnInfo);
        Integer loginType = Integer.valueOf(loginTypeStr);
        try {
            BaseResponse<User> response = userService.trdPtyLogin(uuid, loginType, returnInfo,src);
            if (response!=null && response.isSuccess()) {
                AppResultBuilder.buildSucResult(result,response.getResult());
            }else{
                AppResultBuilder.buildErrorResult(result, response.getError_code(), "Service Error", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppResultBuilder.buildProcessErrorResult(result, ErrorCode.PROCESS_ERROR.getError_msg(), "Service Error");
        }

    }

    // http://motif.evermarker.com/user?cmd=signout&pin=kdd&token=199999999999
    // 退出登录
    public void signOut(HttpServletRequest req,JSONObject result){
        String pin = req.getParameter(FieldSchema.PIN);
        String token = req.getParameter(FieldSchema.TOKEN);
        if(StringUtils.isEmpty(pin) || StringUtils.isEmpty(token)){
            AppResultBuilder.buildParamErrorResult(result,"pin token null","");
            return;
        }
        BaseResponse<Boolean> response = null;
        try {
            response = userService.signOut(pin,token);
            if (response!=null && response.isSuccess()) {
                AppResultBuilder.buildSucResult(result,new Object());
            }else{
                AppResultBuilder.buildErrorResult(result, response.getError_code(), response.getError_msg(), "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppResultBuilder.buildProcessErrorResult(result, ErrorCode.PROCESS_ERROR.getError_msg(), "Service Error");
        }

    }

    //// uuid pin token nickname icon
    //  http://motif.evermarker.com/user?cmd=modify&pin=kdd&token=199999999999&nick=kangdong&icon=icon_url
    // 修改信息
    public void modifyUserInfo(HttpServletRequest req,JSONObject result){
        String pin = req.getParameter(FieldSchema.PIN);
        if(StringUtils.isEmpty(pin) ){
            AppResultBuilder.buildParamErrorResult(result,"pin is null","");
            return;
        }
        UserModel userModel=null;
        try {
            userModel = ParamProcessor.processorUser(pin,req);
        }  catch (ParamException e) {
            e.printStackTrace();
            AppResultBuilder.buildParamErrorResult(result,e.getMessage(),"Param Erro");
        }
        BaseResponse<Boolean> response = null;
        try {
            response = userService.modifyUserInfo(userModel);
            if (response!=null && response.isSuccess()) {
                AppResultBuilder.buildSucResult(result,new Object());
            }else{
                AppResultBuilder.buildErrorResult(result, response.getError_code(), response.getError_msg(), "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppResultBuilder.buildProcessErrorResult(result,  ErrorCode.PROCESS_ERROR.getError_msg(), "Service Error");
        }
    }

    //  http://motif.evermarker.com/user?cmd=forgetpwd&token=199999999999&email=kangdongno.1@evermarker.net&uuid=11111
    //  忘记密码
    public void forgetPasswd(HttpServletRequest req,JSONObject result){
        String uuid = req.getParameter(FieldSchema.UUID);
        String email = req.getParameter(FieldSchema.EMAIL);
        if(StringUtils.isEmpty(uuid) || StringUtils.isEmpty(email) ){
            AppResultBuilder.buildParamErrorResult(result,"email or uuid is null","");
            return;
        }
        BaseResponse<User> response = null;
        try {
            response = userService.forgotPWD(email);
            if (response!=null && response.isSuccess()) {
                AppResultBuilder.buildSucResult(result, new Object());
            }else if(response!=null && response.getError_code() ==  ErrorCode.USERSTATUS_FORGETPWD_EMIAL_NOT_REGISTERED.getCode()){
                AppResultBuilder.buildErrorResult(result,response.getError_code(),response.getError_msg(),response.getError_msg());
            }else{
                AppResultBuilder.buildErrorResult(result, response.getError_code(), response.getError_msg(), "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppResultBuilder.buildProcessErrorResult(result,  ErrorCode.PROCESS_ERROR.getError_msg(), "Service Error");
        }
    }

    //  http://motif.evermarker.com/user?cmd=modifypwd&token=199999999999&pin=2fed8e13f80a4980a86437d4f6dd5917&oldpw=dfafdasEFDdadfa&pw=11111
    //  修改密码
    public void modifyPasswd(HttpServletRequest req,JSONObject result){
        String pin = req.getParameter(FieldSchema.PIN);
        String oldPwd = req.getParameter(FieldSchema.OLDPASSWD);
        if(StringUtils.isEmpty(pin) || StringUtils.isEmpty(oldPwd) ){
            AppResultBuilder.buildParamErrorResult(result,"pin or oldpwd is null","pin or oldpwd is null");
            return;
        }
        UserModel userModel=null;
        try {
            userModel = ParamProcessor.processorUser(pin,req);
        }  catch (ParamException e) {
            e.printStackTrace();
            AppResultBuilder.buildParamErrorResult(result,e.getMessage(),"Param Err");
        }
        BaseResponse<Boolean> response = null;
        try {
            response = userService.modifyUserPWD(userModel,oldPwd);
            if (response!=null && response.isSuccess()) {
                AppResultBuilder.buildSucResult(result,new Object());
            }else{
                AppResultBuilder.buildErrorResult(result, response.getError_code(), response.getError_msg(), response.getError_msg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppResultBuilder.buildProcessErrorResult(result,  ErrorCode.PROCESS_ERROR.getError_msg(), "Service Error");
        }
    }

    //  http://motif.evermarker.com/user?cmd=modifyfgttpwd&pw=asdfasf&tp=asdfafafasqwerv&sig=sdfgwerggggggg
    /**
     * 忘记密码-修改密码
     * @param req
     * @param result
     */
    public void modifyFgtPwd(HttpServletRequest req,JSONObject result){
        // 防止：多次点击此链接或者没有点击过忘记密码但是链接复制出来修改然后点击
        String pw = req.getParameter(FieldSchema.PASSWD);
        String tp = req.getParameter("tp");
        String sig = req.getParameter("sig");

        if(StringUtils.isEmpty(pw) ||StringUtils.isEmpty(tp)
                || StringUtils.isEmpty(sig)){
            AppResultBuilder.buildParamErrorResult(result,"pw or tp or sig is null","");
            return;
        }

        BaseResponse<Boolean> response = null;
        try {
            response = userService.modifyFgtPwd(pw,tp,sig);
            if (response!=null && response.isSuccess()) {
                AppResultBuilder.buildSucResult(result,new Object());
            }else{
                AppResultBuilder.buildErrorResult(result, response.getError_code(), response.getError_msg(), "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppResultBuilder.buildProcessErrorResult(result,  ErrorCode.PROCESS_ERROR.getError_msg(), "Service Error");
        }
    }

    //  http://motif.evermarker.com/user?cmd=uploadicon&pin=asdfafafawrqwe&token=asdfafadfafaf
    /**
     * 上传头像，其实这个功能应该叫上传图片，他仅仅是把图片上传到亚马逊，然后返回路径给客户端，不涉及其他的业务逻辑
     * 目前不对图片类型做限制
     * 那上传头像来说：这里上传图片，然后返回图片路径，客户端根据图片路径再次请求修改用户数据接口（cmd=modify）
     * @param req
     * @param result
     */
    public void uploadIcon(HttpServletRequest req,JSONObject result){
        String pin = req.getParameter(FieldSchema.PIN);
        if(StringUtils.isEmpty(pin) ){
            AppResultBuilder.buildParamErrorResult(result,"pin null","");
            return;
        }

        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        //可以不设置缓冲区目录和大小
//        String basePath = req.getServletContext().getRealPath("/");
//        File repository = new File(basePath); //缓存区目录
//        int sizeThreshold=102400; //缓存区大小
//        diskFileItemFactory.setRepository(repository);
//        diskFileItemFactory.setSizeThreshold(sizeThreshold);

//        FileItemFactory必须进行设置，否则报错如下：java.lang.NullPointerException: No FileItemFactory has been set.
        ServletFileUpload servletFileUpload=new ServletFileUpload(diskFileItemFactory);
        long sizeMax = 52428880 ;//1024 * 1024 * 5;// 设置文件的大小为5M
        servletFileUpload.setSizeMax(sizeMax);

        try{
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);
            boolean uf = false;
            for(FileItem fileItem:fileItems){
                //或者利用fileItem.isFormField()进行判断，为true说明不是文件对象
                String filePath = fileItem.getName();
                //System.out.println("filePath:"+filePath);
                if(filePath==null || filePath.trim().length()==0) {
                    continue;
                }
                // 测试输出文件
//                String fileName=filePath.substring(filePath.lastIndexOf(File.separator)+1);
//                FileOutputStream fos = new FileOutputStream(new File(basePath+File.separator+fileName));
//                InputStream ins = fileItem.getInputStream();
//                byte[] b = new byte[102400];
//                int len = -1;
//                while((len = ins.read(b)) > -1){
//                    fos.write(b,0,len);
//                }
//                fos.flush();
//                fos.close();
        // 输出文件到指定对象
//                try {
//                    fileItem.write(new File(basePath+File.separator+fileName));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                InputStream ins = fileItem.getInputStream();
                BaseResponse<ImgUpS3Response> response = ImageServiceImpl.upCidIconImg(ins);
                if(response!=null && response.isSuccess()){
//                    String amazonPath = "https://s3-us-west-1.amazonaws.com/emimagetest/" + response.getResult().getShowImageLink();
                    HashMap<String,String> map = new HashMap<String, String>();

                    map.put("url",response.getResult().getImageLink());
                    AppResultBuilder.buildSucResult(result,map);
                }else{
                    AppResultBuilder.buildErrorResult(result, response.getError_code(), response.getError_msg(), "");
                }
                if(ins != null){
                    ins.close();
                }
                //因为这里是单文件上传，所以直接break。
                uf = true;
                break;
            }
            if(!uf){
                AppResultBuilder.buildErrorResult(result,ErrorCode.Other_Error,"Param error");
            }
        }catch(FileUploadBase.FileSizeLimitExceededException e){
            AppResultBuilder.buildErrorResult(result,ErrorCode.Other_Error.getCode(),ErrorCode.Other_Error.getError_msg(), " file size is not allowed");
        }catch(Exception e){
            e.printStackTrace();
            AppResultBuilder.buildProcessErrorResult(result,  ErrorCode.PROCESS_ERROR.getError_msg(), "Service Error");
        }
    }


    public void getThirdPartyLoginEmail(HttpServletRequest req,JSONObject result){
        // 防止：多次点击此链接或者没有点击过忘记密码但是链接复制出来修改然后点击
        String thirdID = req.getParameter(FieldSchema.THIRD_ID);
        String loginTypeStr = req.getParameter(FieldSchema.LOGIN_TYPE);

        if(StringUtils.isEmpty(thirdID)  || StringUtils.isEmpty(loginTypeStr)){
            AppResultBuilder.buildParamErrorResult(result,"third login token null or login_type null","");
            return;
        }
        int loginType = Integer.valueOf(loginTypeStr);
        BaseResponse<String> response = null;
        try {
            response = userService.getThirdLoginEmail(thirdID,loginType);
            if (response!=null && response.isSuccess()) {
                if(response.getResult()!=null){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("email",response.getResult());
                    AppResultBuilder.buildSucResult(result,jsonObject);
                }else{
                    AppResultBuilder.buildSucResult(result,new Object());
                }
            }else{
                AppResultBuilder.buildErrorResult(result, response.getError_code(), ErrorCode.PROCESS_ERROR.getError_msg(),"");
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppResultBuilder.buildProcessErrorResult(result, ErrorCode.PROCESS_ERROR.getError_msg(), "Service Error");
        }
    }
    public void getUseInviteCode(HttpServletRequest req,JSONObject result){
        String pin = req.getParameter(FieldSchema.PIN);
        if(StringUtils.isEmpty(pin)){
            AppResultBuilder.buildParamErrorResult(result,"pin null","");
            return ;
        }
        try{
            BaseResponse<String> response = userService.getInviteCode(pin);
            if(response.isSuccess()){
                HashMap<String,String> data = new HashMap<String, String>();
                data.put("invite_code",response.getResult());
                AppResultBuilder.buildSucResult(result,data);
            }else{
                AppResultBuilder.buildErrorResult(result, response.getError_code(), "Param Error","");
            }
        }catch (Exception e){
            e.printStackTrace();
            AppResultBuilder.buildProcessErrorResult(result,ErrorCode.PROCESS_ERROR.getError_msg(),"Service Error");
        }
    }
}
